package com.online.action.util;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.io.FileUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import com.online.model.user.UserInfo;
import com.online.util.ExcelConfig;
import com.online.util.ExcelUtil;

/**
 * 常用工具方法
 * 
 * @author trunks
 * 
 */
@Controller
@RequestMapping("/util")
public class UtilAction {

	@RequestMapping("upload")
	public String upload() {
		return "/util/upload.jsp";
	}

	/** 单文件上传 */
	@RequestMapping("singleUpload")
	public String singleUpload(@RequestParam MultipartFile photo, RedirectAttributes redirectAttributes) {
		System.out.println("===ContentType：" + photo.getContentType());
		System.out.println("===上传控件名：" + photo.getName());
		System.out.println("===原始文件名：" + photo.getOriginalFilename());
		String msg = "上传文件成功";

		try {
			if (StringUtils.isNotBlank(photo.getOriginalFilename())) {
				File target = new File("D:/不存在的文件夹/" + photo.getOriginalFilename());
				target.getParentFile().mkdirs();
				photo.transferTo(target);
			}
		} catch (IOException e) {
			msg = "上传文件失败：" + e.getMessage();
			e.printStackTrace();
		}
		redirectAttributes.addFlashAttribute("msg", msg);
		return "redirect:/util/upload";
	}

	/** 多文件上传 */
	@RequestMapping("multiUpload")
	public String multiUpload(@RequestParam MultipartFile[] photos, RedirectAttributes redirectAttributes) {
		String msg = "上传文件成功";

		try {
			for (MultipartFile photo : photos) {
				if (StringUtils.isNotBlank(photo.getOriginalFilename())) {
					File target = new File("D:/不存在的文件夹/" + photo.getOriginalFilename());
					target.getParentFile().mkdirs();
					photo.transferTo(target);
				}
			}
		} catch (IOException e) {
			msg = "上传文件失败：" + e.getMessage();
			e.printStackTrace();
		}
		redirectAttributes.addFlashAttribute("msg", msg);
		return "redirect:/util/upload";
	}

	/** 文件下载 */
	@RequestMapping("download")
	public ResponseEntity<byte[]> download(HttpServletRequest request) throws IOException {
		String path = request.getSession().getServletContext().getRealPath("/");
		HttpHeaders head = new HttpHeaders();
		File file = new File(path + "/resources/js/jquery.form-3.24.js");

		head.setContentType(MediaType.APPLICATION_OCTET_STREAM);
		// 下载的文件名
		head.setContentDispositionFormData("attachment", new String(file.getName().getBytes("UTF-8"), "ISO8859-1"));
		return new ResponseEntity<byte[]>(FileUtils.readFileToByteArray(file), head, HttpStatus.CREATED);
	}

	/**
	 * 导出Excel。 目前会遗留生成的Excel文件问题。考虑用直接用OutputStream解决。
	 */
	@RequestMapping("exportExcel")
	public ResponseEntity<byte[]> exportExcel(HttpServletRequest request) throws Exception {
		String path = request.getSession().getServletContext().getRealPath("/");
		HttpHeaders head = new HttpHeaders();
		File file = new File(path + "/resources/导出Excel.xlsx");
		ExcelConfig config = new ExcelConfig();

		// 先生成Excel文件
		config.setSourceTemplate(path + "/resources/template.xlsx");
		config.setTargetFile(path + "/resources/导出Excel.xlsx");
		config.setData(createData(65000));
		config.setAutoSize(true);
		config.setPageSize(10);
		config.setSumColumn(new String[] { "age" });
		new ExcelUtil(config).writeExcel();
		head.setContentType(MediaType.APPLICATION_OCTET_STREAM);
		// 下载的文件名
		head.setContentDispositionFormData("attachment", new String(file.getName().getBytes("UTF-8"), "ISO8859-1"));
		return new ResponseEntity<byte[]>(FileUtils.readFileToByteArray(file), head, HttpStatus.CREATED);
	}

	private List<UserInfo> createData(int total) {
		List<UserInfo> users = new ArrayList<UserInfo>();
		for (int i = 0; i < total; i++) {
			UserInfo user = new UserInfo();
			user.setId(i);
			user.setAge(25);
			user.setName("技术员" + i);
			users.add(user);
		}
		return users;
	}
}
